/*
    BEEM is a videoconference application on the Android Platform.

    Copyright (C) 2009 by Frederic-Charles Barthelery,
                          Jean-Manuel Da Silva,
                          Nikita Kozlov,
                          Philippe Lago,
                          Jean Baptiste Vergely,
                          Vincent Veronis.

    This file is part of BEEM.

    BEEM is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BEEM is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BEEM.  If not, see <http://www.gnu.org/licenses/>.

    Please send bug reports with examples or suggestions to
    contact@beem-project.com or http://dev.beem-project.com/

    Epitech, hereby disclaims all copyright interest in the program "Beem"
    written by Frederic-Charles Barthelery,
               Jean-Manuel Da Silva,
               Nikita Kozlov,
               Philippe Lago,
               Jean Baptiste Vergely,
               Vincent Veronis.

    Nicolas Sadirac, November 26, 2009
    President of Epitech.

    Flavien Astraud, November 26, 2009
    Head of the EIP Laboratory.

*/
package com.beem.project.beem.ui;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.jivesoftware.smack.packet.Presence.Mode;
import org.jivesoftware.smack.util.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;

import com.awan.adapter.EmoticonAdapter;
import com.awan.adapter.StickerAdapter;
import com.awan.controller.StickerCategoryItem;
import com.awan.controller.StickerDetailItem;
import com.awan.model.ChatDatabaseHandler;
import com.awan.utils.Base64;
import com.awan.utils.Constanta;
import com.awan.utils.GeneralStatic;
import com.awan.utils.HttpUtilsPost;
import com.awan.utils.netStatus;
import com.beem.project.beem.BeemApplication;
import com.beem.project.beem.R;
import com.beem.project.beem.providers.AvatarProvider;
import com.beem.project.beem.service.Contact;
import com.beem.project.beem.service.LoginAsyncTask;
import com.beem.project.beem.service.Message;
import com.beem.project.beem.service.PresenceAdapter;
import com.beem.project.beem.service.aidl.IBeemRosterListener;
import com.beem.project.beem.service.aidl.IChat;
import com.beem.project.beem.service.aidl.IChatManager;
import com.beem.project.beem.service.aidl.IChatManagerListener;
import com.beem.project.beem.service.aidl.IMessageListener;
import com.beem.project.beem.service.aidl.IRoster;
import com.beem.project.beem.service.aidl.IXmppFacade;
import com.beem.project.beem.ui.dialogs.builders.ChatList;
import com.beem.project.beem.ui.dialogs.builders.DisplayOtrFingerprint;
import com.beem.project.beem.utils.BeemBroadcastReceiver;
import com.beem.project.beem.utils.Status;
import com.conte.services.global;
import com.dheina.lazylist.ImageLoader;

import de.duenndns.ssl.MemorizingTrustManager;

/**
 * This class represents an activity which allows the user to chat with his/her contacts.
 * @author Jean-Manuel Da Silva <dasilvj at beem-project dot com>
 */
public class Chat extends Activity implements TextView.OnEditorActionListener, OnClickListener {

    private static final String TAG = "Chat";
    private static final Intent SERVICE_INTENT = new Intent();
    static {
	SERVICE_INTENT.setComponent(new ComponentName("com.beem.project.beem", "com.beem.project.beem.BeemService"));
    }
    private Handler mHandler = new Handler();

    private IRoster mRoster;
    private Contact mContact;

    private TextView mContactNameTextView;
    private TextView mContactStatusMsgTextView;
    private TextView mContactChatState;
    //private TextView mContactOtrState;
    private ImageView mContactStatusIcon;
    private LayerDrawable mAvatarStatusDrawable;
    private ListView mMessagesListView;
    private EditText mInputField;
    //private Button mSendButton;
    private ImageView mSendButton;
    private final Map<Integer, Bitmap> mStatusIconsMap = new HashMap<Integer, Bitmap>();

    private final List<MessageText> mListMessages = new ArrayList<MessageText>();

    private IChat mChat=null;
    private IChatManager mChatManager=null;
    private final IMessageListener mMessageListener = new OnMessageListener();
    private final IChatManagerListener mChatManagerListener = new ChatManagerListener();
    private MessagesListAdapter mMessagesListAdapter;// = new MessagesListAdapter();

    private final ServiceConnection mConn = new BeemServiceConnection();
    private final BeemBroadcastReceiver mBroadcastReceiver = new BeemBroadcastReceiver();
    private final BeemRosterListener mBeemRosterListener = new BeemRosterListener();
    private IXmppFacade mXmppFacade=null;
    private String mCurrentAvatarId;
    private boolean mBinded;
    private boolean mCompact;
    private StickerAdapter mAdapter;
    
    private ImageView emoticonImage;
    private ArrayList<Integer> emoList;
    
    private SharedPreferences settings;
    private SharedPreferences.Editor settingsEditor;// = settings.edit();
    
    private ChatDatabaseHandler db;
    private Dialog loadingDialog;
    
    private File attachmentFiles;
    private static Context cntx;
    private static Activity act;
    private BeemApplication session;

    /**
     * Constructor.
     */
    public Chat() {
    	super();
    	emoList = Constanta.getEmoList();    	
    }          
    
    //TempListAdapter tmpListAdapter;
    
    private ImageLoader imageLoader;
    private Bundle b;
    ImageView closeButtonMenu;
    
    private ProgressBar uploadProgress;
    private ImageView attachmentFile;
    
    private Intent intent = new Intent();
    
    /**
     * {@inheritDoc}.
     */
    @Override
    protected void onCreate(Bundle savedBundle) {
    	
		super.onCreate(savedBundle);
		mContact = new Contact(getIntent().getData());
		loadingDialog = GeneralStatic.getDialogProgress(this);
		//Log.e(TAG, "onCreate");
		
		cntx = this;
		act=this;
		session=((BeemApplication)getApplicationContext());
		
		imageLoader = new ImageLoader(this);
		
		
		this.registerReceiver(mBroadcastReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));
		settings = PreferenceManager.getDefaultSharedPreferences(this);
		settingsEditor = settings.edit();
		mCompact = settings.getBoolean(BeemApplication.USE_COMPACT_CHAT_UI_KEY, false);		
		
		myName = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		myName = myName.replace("@"+Constanta.chatDomain, "");
		
		if (!mCompact) {
		    setContentView(R.layout.chat);
		    mContactNameTextView = (TextView) findViewById(R.id.chat_contact_name);
		    mContactStatusMsgTextView = (TextView) findViewById(R.id.chat_contact_status_msg);
		    mContactChatState = (TextView) findViewById(R.id.chat_contact_chat_state);
		    mContactStatusIcon = (ImageView) findViewById(R.id.chat_contact_status_icon);
		   //@ mAvatarStatusDrawable = (LayerDrawable) mContactStatusIcon.getDrawable();
		    //mContactOtrState = (TextView) findViewById(R.id.chat_contact_otr_state);
		    //@ mAvatarStatusDrawable.setLayerInset(1, 80, 80, 0, 0);
		} else {
		    setContentView(R.layout.chat_compact);		    
		}
		b = getIntent().getBundleExtra("data");	
		db = new ChatDatabaseHandler(this);
    
		closeButtonMenu = (ImageView)findViewById(R.id.closeImage);
	    closeButtonMenu.setOnClickListener(this/*new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		}*/);

		mMessagesListView = (ListView) findViewById(R.id.chat_messages);
		
		//tmpListAdapter = new TempListAdapter();
		addFromDatabaseMsg();
		mMessagesListAdapter = new MessagesListAdapter();
		
		mMessagesListView.setAdapter(mMessagesListAdapter);
		
		mMessagesListAdapter.notifyDataSetChanged();
		
		//mMessagesListView.setAdapter(tmpListAdapter);
		
		mInputField = (EditText) findViewById(R.id.chat_input);
		mInputField.setOnEditorActionListener(this);
		mInputField.requestFocus();
		//mSendButton = (Button) findViewById(R.id.chat_send_message);
		mSendButton = (ImageView) findViewById(R.id.chat_send_message);
		mSendButton.setOnClickListener(this/*new OnClickListener() {
		    //@Override
		    public void onClick(View v) {
		    	
		    	sendMessage();
		    }
		}*/);
	
		prepareIconsStatus();
		
		emoticonImage = (ImageView)findViewById(R.id.chat_emoticon_popup);
		emoticonImage.setOnClickListener(this);
		
		uploadProgress = (ProgressBar)findViewById(R.id.uploadprogress);
		
		attachmentFile = (ImageView)findViewById(R.id.imageView1);
		attachmentFile.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				AlertDialog.Builder attachmentDialogBuilder;   
		        Context mContext = Chat.this;   
		        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);   
		        //View attachLayout = inflater.inflate(R.layout.attachment_popup,(ViewGroup) findViewById(R.id.chargeWebView));
		        View attachLayout = inflater.inflate(R.layout.chat_media_attach,(ViewGroup) findViewById(R.id.chargeWebView));
		        attachmentDialogBuilder = new AlertDialog.Builder(mContext);  
		        attachmentDialogBuilder.setTitle("Send Attachment");
		        attachmentDialogBuilder.setView(attachLayout);   
		        final Dialog attachDialog = attachmentDialogBuilder.create();
		        attachDialog.show();
		        
		        ImageView captureFoto = (ImageView)attachLayout.findViewById(R.id.imageView2);
		        ImageView getFoto = (ImageView)attachLayout.findViewById(R.id.imageView1);
		        //ImageView captureVideo = (ImageView)attachLayout.findViewById(R.id.imageView4);
		        ImageView getVideo = (ImageView)attachLayout.findViewById(R.id.imageView3);
		        ImageView getAudio = (ImageView)attachLayout.findViewById(R.id.imageView4);
		        
		        /*
		         * Capture Foto
		         * */
		        captureFoto.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub attachmentFile						
						FILE_DIR.mkdirs();
						attachmentFiles = new File(FILE_DIR, getPhotoFileName());
						 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
					     intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(attachmentFiles));
					     startActivityForResult(intent, 1888);						
					     attachDialog.dismiss();
					}
				});
		        
		        /*
		         * Get Foto
		         * */
		        getFoto.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent i = new Intent(Intent.ACTION_PICK,
					               android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						i.setType("image/*");
						startActivityForResult(i, 1889);
						 attachDialog.dismiss();
					}
				});
		        
		        /*
		         * Capture Video
		         * */
		       /* captureVideo.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub						
						FILE_DIR.mkdirs();
						attachmentFiles = new File(FILE_DIR, getVideoFileName());
						 Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE, null);
						 intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
					     startActivityForResult(intent, 1891);						
					     attachDialog.dismiss();
					}
				});*/
		        
		        /*
		         * Get Video
		         * */
		        getVideo.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent i = new Intent(Intent.ACTION_PICK,
					               android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
						i.setType("video/*");
						startActivityForResult(i, 1890);
						 attachDialog.dismiss();
					}
				});
		        
		        /*getAudio.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent i = new Intent(Intent.ACTION_PICK,
					               android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
						i.setType("video/mp3");
						startActivityForResult(i, 1899);
						 attachDialog.dismiss();
					}
				});*/
			}
		});
		
		setUserAvatar();
		
    } 
    private static final File FILE_DIR = new File(Environment.getExternalStorageDirectory() + "/android/data/smiles/Camera");
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }
    private String getVideoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'VID'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".3gp";
    }
    
    private void showUploadProgress(){
    	attachmentFile.setVisibility(View.INVISIBLE);
    	uploadProgress.setVisibility(View.VISIBLE);
    }
    private void hideUploadProgress(){
    	attachmentFile.setVisibility(View.VISIBLE);
    	uploadProgress.setVisibility(View.INVISIBLE);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	// TODO Auto-generated method stub
    	if (requestCode == 1888 && resultCode == RESULT_OK) {    		
    		new FileUploadTask().execute();	
        }else if(requestCode == 1889 && resultCode == RESULT_OK){
        	Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex); 
            cursor.close();            
            attachmentFiles = new File(filePath);
            new FileUploadTask().execute();	
        }else if(requestCode == 1890 && resultCode == RESULT_OK){
        	Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex); 
            cursor.close();            
            attachmentFiles = new File(filePath);
            new FileUploadTask().execute();	
        }else if (requestCode == 1891 && resultCode == RESULT_OK) {        	
        	try {
        	    AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
        	    FileInputStream fis = videoAsset.createInputStream();
        	    File tmpFile = new File(Environment.getExternalStorageDirectory()+ "/android/data/smiles/Camera", getVideoFileName()); 
        	    FileOutputStream fos = new FileOutputStream(tmpFile);
        	    byte[] buf = new byte[1024];
        	    int len;
        	    while ((len = fis.read(buf)) > 0) {
        	        fos.write(buf, 0, len);
        	    }       
        	    fis.close();
        	    fos.close();        	    
        	    attachmentFiles = tmpFile;
        	    new FileUploadTask().execute();	        	    
        	  } catch (IOException io_e) {}
        }/*else if(requestCode == 1899 && resultCode == RESULT_OK){
        	Uri selectedAudio = data.getData();
            String[] filePathColumn = {MediaStore.Audio.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedAudio, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex); 
            cursor.close();            
            attachmentFiles = new File(filePath);
            new FileUploadTask().execute();	
        }*/
    }
    
    /*
     * upload attachment
     * */
    
    private class FileUploadTask extends AsyncTask <String, Integer, String>{
    	
    	public FileUploadTask(){
    		showUploadProgress();
    		/*mProgressDialog = new ProgressDialog(cntx);
			mProgressDialog.setMessage("Uploading...");
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);*/
    	}
    	
		protected String doInBackground(String... unsued) {
			
			try {
				
				String fromName = myName;
				String toName = mContact.getName();
				toName = toName.replace("@"+Constanta.chatDomain, "");
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpContext localContext = new BasicHttpContext();
				HttpPost httpPost = new HttpPost(Constanta.apiSendFile);
				
				MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

				byte[] data = FileUtils.readFileToByteArray(attachmentFiles);
	            
				entity.addPart("username", new StringBody(fromName));
				entity.addPart("to_name", new StringBody(toName));
				entity.addPart("file", new ByteArrayBody(data, attachmentFiles.getAbsolutePath()));
				
				httpPost.setEntity(entity);
				
				HttpResponse response = httpClient.execute(httpPost, localContext);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(
								response.getEntity().getContent(), "UTF-8"));
				
				/*int bufferLength = 1024;
				for (int i = 0; i < data.length; i += bufferLength) {
					int progress = (int)((i / (float) data.length) * 100);
					publishProgress(progress);
					//wait(100);
				}
				publishProgress(100);*/
				
				String sResponse = reader.readLine();
				
				return sResponse;
				
			} catch (final Exception e) {
				runOnUiThread(new Runnable() {					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Toast.makeText(getApplicationContext(),
								"error upload ... "+e.getMessage(),
								Toast.LENGTH_LONG).show();
					}
				});				
				Log.e(e.getClass().getName(), e.getMessage(), e);
				return null;
			}
		}

		 protected void onProgressUpdate(Integer... progress) {
		        super.onProgressUpdate(progress);
		        mProgressDialog.setProgress(progress[0]);
		    }
		
		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			//mProgressDialog.show();
		}
		@Override
		protected void onPostExecute(String sResponse) {
			hideUploadProgress();
			//mProgressDialog.dismiss();
			try {
				if (sResponse != null) {
					
					JSONObject jsonResponse = new JSONObject(sResponse);	
    				
					String status = jsonResponse.getString("STATUS");

    				if(status.trim().equalsIgnoreCase("SUCCESS")){
    					String fileUrl = jsonResponse.getString("FILE_URL");
        				//String senderId = jsonResponse.getString("USER_ID");
    					Toast.makeText(getApplicationContext(),
								"uploaded status : " + status,
								Toast.LENGTH_SHORT).show();
    					String fileToPath = /*Constanta.apiUserDirPath+"/"+senderId+"/uploads/"+*/fileUrl;
    					mInputField.setText("fileattachment:"+fileToPath+"|"+attachmentFiles.getAbsolutePath());
    					sendMessage();
    				}else{
    					String msg = jsonResponse.getString("MESSAGE");
    					Toast.makeText(getApplicationContext(), status+":"+msg,
								Toast.LENGTH_LONG).show();
    				}
				}
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(),
						"error:"+e.getMessage(),
						Toast.LENGTH_LONG).show();
				Log.e(e.getClass().getName(), e.getMessage(), e);
			}
		}

		
	}
    
    private void setUserAvatar(){
    	if(b != null){
	    	final String avatarUrl = b.getString("avatarurl");
			final String jid = b.getString("jid");			
						
			Bitmap bitmap = imageLoader.getBitmapCache(avatarUrl);			
			if(bitmap == null){				
				new Thread(){
					public void run(){
						String getProfileUrl = Constanta.apiUserProfile;
						Map<String, String> formParameters = new HashMap<String, String>();
						formParameters.put("username", jid);
						formParameters.put("targetname", jid);
						try {
							String profileRequest = HttpUtilsPost.post(getProfileUrl, Constanta.requestHeaders(), formParameters, null);
							JSONObject jsonResponse = new JSONObject(profileRequest);	
							String status = jsonResponse.getString("STATUS");
							if(status.trim().equalsIgnoreCase("SUCCESS")){
								JSONObject profileDetail = new JSONObject(jsonResponse.getString("DATA"));	
								final String avatarUrl = profileDetail.getString("avatar");
								runOnUiThread(new Runnable() {									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										imageLoader.DisplayImage(avatarUrl, mContactStatusIcon);
									}
								});								
							}
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ProtocolException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}finally{
							this.interrupt();
						}
					}
				}.start();
			}
	    }else{
	    	Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.no_avatar);
	    	mContactStatusIcon.setImageBitmap(bitmap);
	    }
    }

    private void addFromDatabaseMsg(){
    	mListMessages.clear();
		List<com.awan.controller.Chat> chatList = db.getAllChat(mContact.getJID());
		for (com.awan.controller.Chat cn : chatList) {
            String self = getString(R.string.chat_self);            
            String theDate = cn.getDate();
            SimpleDateFormat  format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");
            Date date = null;
            try {
				date = format.parse(theDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}             
            if(self.trim().equalsIgnoreCase(cn.getFrom())){
            	mListMessages.add(new MessageText(self, self, cn.getMsg(), false, date));
            }else{            	
            	mListMessages.add(new MessageText(cn.getFrom(), mContact.getName(), cn.getMsg(), false, date));
            }
		}
		//Log.e(TAG, "mListMessages count : " + mListMessages.size());
		
    }
    
    @Override
    protected void onResume() {
		super.onResume();
		
		/*Log.e(TAG, "onResume");*/
		
		if (!mBinded) {
		    bindService(SERVICE_INTENT, mConn, BIND_AUTO_CREATE);
		    mBinded = true;
		}
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	//Log.e(TAG, "onDestroy");
    	this.unregisterReceiver(mBroadcastReceiver);
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    protected void onPause() {
		super.onPause();
		//Log.e(TAG, "onPause");
		try {
		    if (mChat != null) {
				mChat.setOpen(false);
				mChat.removeMessageListener(mMessageListener);
		    }
		    if (mRoster != null)
		    	mRoster.removeRosterListener(mBeemRosterListener);
		    if (mChatManager != null)
		    	mChatManager.removeChatCreationListener(mChatManagerListener);
		} catch (RemoteException e) {
		    Log.e(TAG, e.getMessage());
		}
		if (mBinded) {
		    unbindService(mConn);
		    mBinded = false;
		}
		mXmppFacade = null;
		mRoster = null;
		mChat = null;
		mChatManager = null;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		//Log.e(TAG, "onNewIntent");
		setIntent(intent);
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState) {
    	super.onSaveInstanceState(savedInstanceState);
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public final boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.chat, menu);
		return true;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public final boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		    case R.id.chat_menu_contacts_list:
			Intent contactListIntent = new Intent(this, ContactList.class);
			contactListIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(contactListIntent);
			break;
		    case R.id.chat_menu_change_chat:
			try {
			    final List<Contact> openedChats = mChatManager.getOpenedChatList();
			    Dialog chatList = new ChatList(Chat.this, openedChats).create();
			    chatList.show();
			} catch (RemoteException e) {
			    Log.e(TAG, e.getMessage());
			}
			break;
		    case R.id.chat_menu_close_chat:
			try {
			    mChatManager.destroyChat(mChat);
			} catch (RemoteException e) {
			    Log.e(TAG, e.getMessage());
			}
			this.finish();
			break;
		    case R.id.chat_menu_start_otr_session:
			try {
			    if (mChat == null) {
				mChat = mChatManager.createChat(mContact, mMessageListener);
				if (mChat != null) {
				    mChat.setOpen(true);
				}
			    }
			    mChat.startOtrSession();
			} catch (RemoteException e) {
			    Log.e(TAG, "start otr chats failed " + mChat, e);
			}
			break;
		    case R.id.chat_menu_stop_otr_session:
			try {
			    if (mChat == null) {
				mChat = mChatManager.createChat(mContact, mMessageListener);
				if (mChat != null) {
				    mChat.setOpen(true);
				}
			    }
			    mChat.endOtrSession();
			} catch (RemoteException e) {
			    Log.e(TAG, "close otr chats failed " + mChat, e);
			}
			break;
		    case R.id.chat_menu_otr_verify_key:
			try {
			    if (mChat == null) {
				mChat = mChatManager.createChat(mContact, mMessageListener);
				if (mChat != null) {
				    mChat.setOpen(true);
				}
			    }
			    Dialog otrDialog = new DisplayOtrFingerprint(this, mChat).create();
			    otrDialog.show();
			} catch (RemoteException e) {
			    Log.e(TAG, "getting local otr key failed " + mChat, e);
			}
			break;
		    default:
			return false;
		}
		return true;
    }

    /**
     * Change the displayed chat.
     * @param contact the targeted contact of the new chat
     * @throws RemoteException If a Binder remote-invocation error occurred.
     */
    private void changeCurrentChat(Contact contact) throws RemoteException {
		if (mChat != null) {
		    mChat.setOpen(false);
		    mChat.removeMessageListener(mMessageListener);
		}
		mChat = mChatManager.getChat(contact);
		if (mChat != null) {
		    mChat.setOpen(true);
		    mChat.addMessageListener(mMessageListener);
		    mChatManager.deleteChatNotification(mChat);
		    updateOtrInformations(mChat.getOtrStatus());
		}
		mContact = mRoster.getContact(contact.getJID());
		String res = contact.getSelectedRes();
		if (mContact == null)
		    mContact = contact;
		if (!"".equals(res)) {
		    mContact.setSelectedRes(res);
		}
		updateContactInformations();
		// @ updateContactStatusIcon();	
		playRegisteredTranscript();
    }

    /**
     * Get all messages from the current chat and refresh the activity with them.
     * @throws RemoteException If a Binder remote-invocation error occurred.
     */
    private void playRegisteredTranscript() throws RemoteException {
		//mListMessages.clear();
		if (mChat != null) {
		    //List<MessageText> msgList = convertMessagesList(mChat.getMessages());
		    //mListMessages.addAll(msgList);
		   // Log.e(TAG, "notify2");
		    addFromDatabaseMsg();
		    mMessagesListAdapter.notifyDataSetChanged();
		}
    }

    /**
     * Convert a list of Message coming from the service to a list of MessageText that can be displayed in UI.
     * @param chatMessages the list of Message
     * @return a list of message that can be displayed.
     */
    private List<MessageText> convertMessagesList(List<Message> chatMessages) {
		List<MessageText> result = new ArrayList<MessageText>(chatMessages.size());
		String remoteName = mContact.getName();
		String localName = getString(R.string.chat_self);
		MessageText lastMessage = null;
	
		for (Message m : chatMessages) {
		    String name = remoteName;
		    String fromBareJid = StringUtils.parseBareAddress(m.getFrom());
		    if (m.getType() == Message.MSG_TYPE_ERROR) {
				lastMessage = null;
				result.add(new MessageText(fromBareJid, name, m.getBody(), true, m.getTimestamp()));
		    } else if  (m.getType() == Message.MSG_TYPE_INFO) {
				lastMessage = new MessageText("", "", m.getBody(), false);
				result.add(lastMessage);
	
		    } else if (m.getType() == Message.MSG_TYPE_CHAT) {
				if (fromBareJid == null) { //nofrom or from == yours
				    name = localName;
				    fromBareJid = "";
				}
		
				if (m.getBody() != null) {
				    if (lastMessage == null || !fromBareJid.equals(lastMessage.getBareJid())) {
						lastMessage = new MessageText(fromBareJid, name, m.getBody(), false, m.getTimestamp());
						result.add(lastMessage);
				    } else {
				    	lastMessage.setMessage(lastMessage.getMessage().concat("\n" + m.getBody()));
				    }
				}
		    }
		}
		return result;
    }

    /**
     * {@inheritDoc}.
     */
    private final class BeemServiceConnection implements ServiceConnection {

		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {}
	
		/**
		 * {@inheritDoc}.
		 */
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    try {
			mRoster = mXmppFacade.getRoster();
			if (mRoster != null)
			    mRoster.addRosterListener(mBeemRosterListener);
			mChatManager = mXmppFacade.getChatManager();
			if (mChatManager != null) {
			    mChatManager.addChatCreationListener(mChatManagerListener);
			    changeCurrentChat(mContact);
			}
		    } catch (RemoteException e) {
		    	Log.e(TAG, e.getMessage());
		    }
		}
	
		/**
		 * {@inheritDoc}.
		 */
		//@Override
		public void onServiceDisconnected(ComponentName name) {
		    mXmppFacade = null;
		    try {
				mRoster.removeRosterListener(mBeemRosterListener);
				mChatManager.removeChatCreationListener(mChatManagerListener);
		    } catch (RemoteException e) {
		    	Log.e(TAG, e.getMessage());
		    }
		}
    }

    /**
     * {@inheritDoc}.
     */
    private class BeemRosterListener extends IBeemRosterListener.Stub {
	
		/**
		 * Constructor.
		 */
		public BeemRosterListener() {}
	
		/**
		 * {@inheritDoc}.
		 */
		//@Override
		public void onEntriesAdded(List<String> addresses) throws RemoteException {
		}
	
		/**
		 * {@inheritDoc}.
		 */
		//@Override
		public void onEntriesDeleted(List<String> addresses) throws RemoteException {
		}
	
		/**
		 * {@inheritDoc}.
		 */
		//@Override
		public void onEntriesUpdated(List<String> addresses) throws RemoteException {
		}
	
		/**
		 * {@inheritDoc}.
		 */
		//@Override
		public void onPresenceChanged(final PresenceAdapter presence) throws RemoteException {
			setUserAvatar();
		    if (mContact.getJID().equals(StringUtils.parseBareAddress(presence.getFrom()))) {
			mHandler.post(new Runnable() {
			   // @Override
			    public void run() {
				mContact.setStatus(presence.getStatus());
				mContact.setMsgState(presence.getStatusText());
				updateContactInformations();
				updateContactStatusIcon();
			    }
			});
		    }
		}
    }

    /**
     * {@inheritDoc}.
     */
    private class OnMessageListener extends IMessageListener.Stub {

		/**
		 * Constructor.
		 */
		public OnMessageListener() {
		}
	
		/**
		 * {@inheritDoc}.
		 */
		//@Override
		public void processMessage(IChat chat, final Message msg) throws RemoteException {
		    final String fromBareJid = StringUtils.parseBareAddress(msg.getFrom());
		    final String self = getString(R.string.chat_self);
		    
		    if (mContact.getJID().equals(fromBareJid)) {
				mHandler.post(new Runnable() {
		
				  //  @Override
				    public void run() {
						if (msg.getType() == Message.MSG_TYPE_ERROR) {
						    mListMessages.add(new MessageText(fromBareJid, mContact.getName(), msg.getBody(), true, msg.getTimestamp()));
						    //Log.e(TAG, "notify3");
						    mMessagesListAdapter.notifyDataSetChanged();
						} else if (msg.getBody() != null) {
						    MessageText lastMessage = null;
						    if (mListMessages.size() != 0)
						    	lastMessage = mListMessages.get(mListMessages.size() - 1);
						    
						    if(msg.getBody().toString().equals("#tsunamiaceh")){
						    	msg.setBody(":P");
					    		Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
					    		vib.vibrate(1000*60);
					    	}
			
						    /*if (lastMessage != null && lastMessage.getBareJid().equals(fromBareJid)  && !lastMessage.toString().contains("stickeranzh")) {
						    	lastMessage.setMessage(lastMessage.getMessage().concat("\n" + msg.getBody()));
						    	lastMessage.setTimestamp(msg.getTimestamp());
						    	mListMessages.set(mListMessages.size() - 1, lastMessage);
						    } else if (msg.getBody() != null)*/
						    
						    //db.addChat(fromBareJid,self, msg.getBody(), msg.getTimestamp().toString(),"");
							mListMessages.add(new MessageText(fromBareJid, mContact.getName(), msg.getBody(), false, msg.getTimestamp()));
							Log.e(TAG, "proses message notify4");
							mMessagesListAdapter.notifyDataSetChanged();
						}
				    }
				});
		    }
		}
	
		/**
		 * {@inheritDoc}.
		 */
		//@Override
		public void stateChanged(IChat chat) throws RemoteException {
			setUserAvatar();
		    final String state = chat.getState();
		    mHandler.post(new Runnable() {
			//@Override
			public void run() {
			    String text = null;
			    if ("active".equals(state)) {
			    	text = Chat.this.getString(R.string.chat_state_active);
			    } else if ("composing".equals(state)) {
			    	text = Chat.this.getString(R.string.chat_state_composing);
			    } else if ("gone".equals(state)) {
			    	text = Chat.this.getString(R.string.chat_state_gone);
			    } else if ("inactive".equals(state)) {
			    	text = Chat.this.getString(R.string.chat_state_inactive);
			    } else if ("paused".equals(state)) {
			    	text = Chat.this.getString(R.string.chat_state_active);
			    }
			    if (!mCompact)
				mContactChatState.setText(text);
			}
		    });
	
		}
	
		//@Override
		public void otrStateChanged(final String otrState) throws RemoteException {
			setUserAvatar();
		    mHandler.post(new Runnable() {
			//@Override
			public void run() {
			    updateOtrInformations(otrState);
			    mListMessages.add(new MessageText("", "", otrState, false));
			    //Log.e(TAG, "notify5");
			    mMessagesListAdapter.notifyDataSetChanged();
			}
		    });
	
		}
    }

    /**
     * Update the contact informations.
     */
    private void updateContactInformations() {
		// Check for a contact name update
    	setUserAvatar();
		String name = mContact.getName();
		String res = mContact.getSelectedRes();
		if (!"".equals(res))
		    name += "(" + res + ")";
		if (!mCompact) {
		    if (!(mContactNameTextView.getText().toString().equals(name)))
			mContactNameTextView.setText(name);
		    //Check for a contact status message update
		    if (!(mContactStatusMsgTextView.getText().toString().equals(mContact.getMsgState()))) {
			mContactStatusMsgTextView.setText(mContact.getMsgState());
			Linkify.addLinks(mContactStatusMsgTextView, Linkify.WEB_URLS);
		    }
		} else {
		    Mode m = Status.getPresenceModeFromStatus(mContact.getStatus());
		    if (m == null)
			setTitle(getString(R.string.chat_name) + " " + name + " ("
			    + getString(R.string.contact_status_msg_offline) + ")");
		    else
			setTitle(getString(R.string.chat_name) + " " + name + " (" + m.name() + ")");
		}
    }

    /**
     * Update the OTR informations.
     * @param otrState the otr state
     */
    private void updateOtrInformations(final String otrState) {
		String text = null;
		setUserAvatar();
		if ("ENCRYPTED".equals(otrState)) {
		    text = Chat.this.getString(R.string.chat_otrstate_encrypted);
		} else if ("FINISHED".equals(otrState)) {
		    text = Chat.this.getString(R.string.chat_otrstate_finished);
		} else if ("AUTHENTICATED".equals(otrState)) {
		    text = Chat.this.getString(R.string.chat_otrstate_authenticated);
		} else {
		    text = Chat.this.getString(R.string.chat_otrstate_plaintext);
		}
		//mContactOtrState.setText(text);
    }

    /**
     * Update the contact status icon.
     */
    private void updateContactStatusIcon() {
    	setUserAvatar();
		if (mCompact)
		    return;
		String id = mContact.getAvatarId();
		if (id == null)
		    id = "";
		//Log.d(TAG, "update contact icon  : " + id);
		if (!id.equals(mCurrentAvatarId)) {
		    Drawable avatar = getAvatarDrawable(mContact.getAvatarId());
		    //mAvatarStatusDrawable.setDrawableByLayerId(R.id.avatar, avatar);
		    mCurrentAvatarId = id;
		}
		// @ mContactStatusIcon.setImageLevel(mContact.getStatus());
    }

    /**
     * Get a Drawable containing the avatar icon.
     * @param avatarId the avatar id to retrieve or null to get default
     * @return a Drawable
     */
    private Drawable getAvatarDrawable(String avatarId) {
		Drawable avatarDrawable = null;
		if (avatarId != null) {
		    Uri uri = AvatarProvider.CONTENT_URI.buildUpon().appendPath(avatarId).build();
		    InputStream in = null;
		    try {
				try {
				    in = getContentResolver().openInputStream(uri);
				    avatarDrawable = Drawable.createFromStream(in, avatarId);
				} finally {
				    if (in != null)
					in.close();
				}
		    } catch (IOException e) {
		    	Log.w(TAG, "Error while setting the avatar", e);
		    }
		}
		if (avatarDrawable == null)
		    avatarDrawable = getResources().getDrawable(R.drawable.no_avatar);
		return avatarDrawable;
    }

    /**
     * Prepare the status icons map.
     */
    private void prepareIconsStatus() {
		mStatusIconsMap.put(Status.CONTACT_STATUS_AVAILABLE,
		    BitmapFactory.decodeResource(getResources(), R.drawable.status_available));
		mStatusIconsMap.put(Status.CONTACT_STATUS_AVAILABLE_FOR_CHAT,
		    BitmapFactory.decodeResource(getResources(), R.drawable.status_available));
		mStatusIconsMap.put(Status.CONTACT_STATUS_AWAY,
		    BitmapFactory.decodeResource(getResources(), R.drawable.status_away));
		mStatusIconsMap.put(Status.CONTACT_STATUS_BUSY,
		    BitmapFactory.decodeResource(getResources(), R.drawable.status_blocked));
		mStatusIconsMap.put(Status.CONTACT_STATUS_DISCONNECT,
		    BitmapFactory.decodeResource(getResources(), R.drawable.status_offline));
		mStatusIconsMap.put(Status.CONTACT_STATUS_UNAVAILABLE,
		    BitmapFactory.decodeResource(getResources(), R.drawable.status_requested));
    }  
    
   /* private class DownloadReceiver extends ResultReceiver{
        public DownloadReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            super.onReceiveResult(resultCode, resultData);
            if (resultCode == DownloadService.UPDATE_PROGRESS) {
                int progress = resultData.getInt("progress");
                mProgressDialog.setProgress(progress);
                if (progress == 100) {
                    mProgressDialog.dismiss();
                }
            }
        }
    }*/
    ProgressDialog mProgressDialog;
    
    /**
     * {@inheritDoc}.
     */
    private class MessagesListAdapter extends BaseAdapter {
	
		/**
		 * Constructor.
		 */
		public MessagesListAdapter() {
			//Log.e(TAG, "MessagesListAdapter:initiate");
		}
	
		/**
		 * Returns the number of messages contained in the messages list.
		 * @return The number of messages contained in the messages list.
		 */
		//@Override
		public int getCount() {
			//Log.e(TAG, "MessagesListAdapter:getCount->"+mListMessages.size());
		    return mListMessages.size();
		}
	
		/**
		 * Return an item from the messages list that is positioned at the position passed by parameter.
		 * @param position The position of the requested item.
		 * @return The item from the messages list at the requested position.
		 */
		//@Override
		public Object getItem(int position) {
			//Log.e(TAG, "MessagesListAdapter:getItem->"+position);
		    return mListMessages.get(position);
		}
	
		/**
		 * Return the id of an item from the messages list that is positioned at the position passed by parameter.
		 * @param position The position of the requested item.
		 * @return The id of an item from the messages list at the requested position.
		 */
		//@Override
		public long getItemId(int position) {
			//Log.e(TAG, "MessagesListAdapter:getItemId->"+position);
		    return position;
		}
	
		/**
		 * Return the view of an item from the messages list.
		 * @param position The position of the requested item.
		 * @param convertView The old view to reuse if possible.
		 * @param parent The parent that this view will eventually be attached to.
		 * @return A View corresponding to the data at the specified position.
		 */
		
		public View getView(int position, View convertView, ViewGroup parent) {
		   //Log.e(TAG, "MessagesListAdapter:getView");
			// View sv;
		   // LayoutInflater inflater;
//		    if (convertView == null) {
//				inflater = Chat.this.getLayoutInflater();
//				sv = inflater.inflate(R.layout.chat_msg_row, null);
//			} else {
//				sv = convertView;
//			}
		    MessageText msg = mListMessages.get(position);
		    String msgValue = msg.getMessage();		
		    
		   // Log.e(TAG, "msgValue:"+msgValue);
		    
		    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);		    
		    String nameIs =  msg.getName();	
		    
		    //Log.e(TAG, "msg :"+msgValue );
		    
		    //LayoutInflater inflater=getLayoutInflater();
		    
		    /*Log.d(TAG, "Message : "+msgValue);
		    Log.d(TAG, "Message Length: "+msgValue.length());
		    Log.d(TAG, "lastMsg : "+lastMsg);*/
		    
		    String lineSep = System.getProperty("line.separator");
		    
		    /*Log.d(TAG, "isNewLine : "+msgValue.contains(lineSep));*/
		    
		    if(msgValue.contains(lineSep)){
	    		String[] splitMessage = msgValue.split(lineSep);
	    		//Log.d(TAG, "the last char"+splitMessage[splitMessage.length-1]);
	    		msgValue = splitMessage[splitMessage.length-1];
	    	}
		    
		    if(msgValue.contains("stickeranzh")){		
		    	
		    	
		    	
		    	//if(stickerInflater==null){
		    		LayoutInflater	stickerInflater = Chat.this.getLayoutInflater();		    		
		    	//}
		    	View stck = stickerInflater.inflate(R.layout.sticker_row, null, false);
		    	//View stck = inflater.inflate(R.layout.sticker_row, null);
		    	ImageView stickerImage = (ImageView)stck.findViewById(R.id.stickerImageView);
		    	TextView msgDates = (TextView) stck.findViewById(R.id.chatmessagedate);
		    	LinearLayout ll = (LinearLayout)stck.findViewById(R.id.stickerparent);
		    	
		    	String[] splitS = msgValue.split(":");
		    	String stickerValue = splitS[1].trim();
		    	
		    	//Log.e(TAG, "stickerValue:"+stickerValue);
		    	
		    	imageLoader.DisplayImage(Base64.decode(stickerValue), stickerImage);
		    	
		    	//stickerImage.setImageResource(Integer.valueOf(stickerValue.trim()));
		    	
		    	if(nameIs.trim().equals("Me")){
		    		ll.setGravity(Gravity.RIGHT);
		    	}else{
		    		ll.setGravity(Gravity.LEFT);
		    	}
		    	if (msg.getTimestamp() != null) {
			    	String date = df.format(msg.getTimestamp());
			    	msgDates.setText(date);
			    }
		    	return stck;
		    	
		    }else if(msgValue.contains("fileattachment")){
		    	
		    	//Log.e(TAG, "msgValue:"+msgValue);
		    	String finalMsg=msgValue.replace("fileattachment:", "");
		    	//Log.e(TAG, "finalMsg : "+finalMsg);
		    	
		    	final String[] explMessage = finalMsg.split("\\|");
		    	
		    	LayoutInflater fileInflater = Chat.this.getLayoutInflater();
		    	View fileAttachButton = fileInflater.inflate(R.layout.chat_filebuton_row, null, false);
		    	LinearLayout ll = (LinearLayout)fileAttachButton.findViewById(R.id.wrapper);
		    	TextView msgDate = (TextView) fileAttachButton.findViewById(R.id.chatmessagedate);
		    	final Button viewFileButton = (Button)fileAttachButton.findViewById(R.id.viewFileButton);
		    	final ImageView attImage=(ImageView)fileAttachButton.findViewById(R.id.chatAttachment);
		    	final ImageLoader img=new ImageLoader(cntx);
		    	final LinearLayout to=(LinearLayout) fileAttachButton.findViewById(R.id.chatAttachmentContainer);
		    	
		    	if(explMessage.length>1){	
		    		
		    		img.DisplayImage(explMessage[0], attImage);
		    		
		    		final String fileToView;
		    		final boolean isLocalFile;
		    		
		    		if(nameIs.trim().equals("Me")){ 	
				    	
				    	to.setBackgroundResource(R.drawable.bubble_green);
				    	to.setGravity(Gravity.RIGHT);
				    	//viewFileButton.setGravity(Gravity.RIGHT);
				    	msgDate.setGravity(Gravity.RIGHT);
				    	ll.setPadding(70, 0, 0, 0);
				    	ll.setGravity(Gravity.RIGHT);
				    	fileToView="file://" +explMessage[1];
				    	isLocalFile=true;
				    	
		    		}else{
		    			
		    			to.setBackgroundResource(R.drawable.bubble_yellow);
				    	to.setGravity(Gravity.LEFT);
				    	//viewFileButton.setGravity(Gravity.LEFT);
				    	msgDate.setGravity(Gravity.LEFT);
				    	ll.setPadding(0, 0, 70, 0);
				    	ll.setGravity(Gravity.LEFT);
				    	fileToView=explMessage[0];
				    	isLocalFile=false;
		    		}
		    		
		    		String[] parseUrl;
		    		
		    		if(!isLocalFile){
		    			parseUrl = fileToView.split("/");
		    			//Log.e(TAG, "file to check:"+parseUrl[parseUrl.length-1]);
		    			String localFilePath = Environment.getExternalStorageDirectory()+ "/android/data/smiles/Camera/"+parseUrl[parseUrl.length-1];
		    			if(!com.awan.utils.FileUtils.fileExists(localFilePath))
		    				viewFileButton.setText("download");
		    		}
		    		
		    		viewFileButton.setOnClickListener(new OnClickListener() {					
						@Override
						public void onClick(View v) {
							
							// TODO Auto-generated method stub
							
							//Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(explMessage[1]));
							//browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							//cntx.startActivity(browserIntent);
							
							//Log.e(getClass().getSimpleName(), "fileToView:"+fileToView);
							
							if(isLocalFile){
								
								Intent browserIntent = new Intent(Intent.ACTION_VIEW);
								
								String dataType = "";
								
								if(fileToView.contains(".3gp"))
									dataType = "video/*";
								else
									dataType = "image/*";

								browserIntent.setDataAndType(Uri.parse(fileToView),dataType);
								browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								cntx.startActivity(browserIntent);
								
							}else{
								
								String[] parseUrl = fileToView.split("/");
								
								Log.e(TAG, "file to check:"+parseUrl[parseUrl.length-1]);
								String localFilePath = Environment.getExternalStorageDirectory()+ "/android/data/smiles/Camera/"+parseUrl[parseUrl.length-1];
								
								if(com.awan.utils.FileUtils.fileExists(localFilePath)){
									
									Intent browserIntent = new Intent(Intent.ACTION_VIEW);
									
									String dataType = "";
									
									if(localFilePath.contains(".3gp"))
										dataType = "video/*";
									else
										dataType = "image/*";
									
									browserIntent.setDataAndType(Uri.parse("file://"+localFilePath),dataType);
									browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
									cntx.startActivity(browserIntent);
									
								}else{
									
									// instantiate it within the onCreate method
									

									// execute this when the downloader must be fired
									DownloadFile downloadFile = new DownloadFile(fileToView);
									downloadFile.execute(fileToView);									
									viewFileButton.setText("view");
									
								}
								
								/*AlertDialog.Builder chargeDialogBuilder;
						        LayoutInflater inflater = (LayoutInflater) cntx.getSystemService(LAYOUT_INFLATER_SERVICE);   
						        View fileLayout = inflater.inflate(R.layout.charge_popup,(ViewGroup) findViewById(R.id.chargeWebView));
						        
						        final WebView fileWebView = (WebView)fileLayout.findViewById(R.id.chargeWebView);
						        chargeDialogBuilder = new AlertDialog.Builder(cntx);  
						        chargeDialogBuilder.setView(fileLayout);   
						        final Dialog fileDialog = chargeDialogBuilder.create();
						        fileDialog.show();
						        fileWebView.loadUrl(fileToView);*/
							}
						}
					});
		    		
		    	}
		    	
		    	if (msg.getTimestamp() != null) {
			    	String date = df.format(msg.getTimestamp());
			    	msgDate.setText(date);
			    }
		    	
		    	return fileAttachButton;
		    	
		    }else{		
		    	
		    	//if(emoticonInflater==null){
		    		LayoutInflater emoticonInflater = Chat.this.getLayoutInflater();
		    	//}
		    	View emo = emoticonInflater.inflate(R.layout.chat_msg_row, null, false);
		    	//View emo = inflater.inflate(R.layout.chat_msg_row, null);
		    	TextView msgText = (TextView) emo.findViewById(R.id.chatmessagetext);
			    TextView msgDate = (TextView) emo.findViewById(R.id.chatmessagedate);		    
			    LinearLayout ll = (LinearLayout)emo.findViewById(R.id.wrapper);
			    
			    //ImageView stickerImage = (ImageView)emo.findViewById(R.id.stickerImageView);
		    	  
		    	if(nameIs.trim().equals("Me")){
			    	// align to right	
			    	msgDate.setGravity(Gravity.LEFT);
			    	msgText.setBackgroundResource(R.drawable.bubble_green);
			    	ll.setGravity(Gravity.RIGHT);
			    	ll.setPadding(70, 0, 0, 0);			    	
			    }else{
			    	// align to left
			    	msgDate.setGravity(Gravity.RIGHT);		    	
			    	ll.setGravity(Gravity.LEFT);
			    	ll.setPadding(0, 0, 70, 0);
			    	msgText.setBackgroundResource(R.drawable.bubble_yellow);		    	
			    }			    
			    msgText.setText(GeneralStatic.getEmoDrawId(msgValue, getResources()), BufferType.SPANNABLE);
			    registerForContextMenu(msgText);
			    if (msg.getTimestamp() != null) {
			    	String date = df.format(msg.getTimestamp());
			    	msgDate.setText(date);
			    }
			    
			    return emo;
			    
		    }
		    //if (msg.isError()) {
		    	//String err = getString(R.string.chat_error);
		    	//msgName.setText(err);
		    	//msgName.setTextColor(Color.RED);
		    	//msgName.setError(err);
		   // }
		   // return sv;
		}
    }

    /**
     * Class which simplify an Xmpp text message.
     * @author Jean-Manuel Da Silva <dasilvj at beem-project dot com>
     */
    private class MessageText {
    	
		private String mBareJid;
		private String mName;
		private String mMessage;
		private boolean mIsError;
		private Date mTimestamp;
	
		/**
		 * Constructor.
		 * @param bareJid A String containing the bare JID of the message's author.
		 * @param name A String containing the name of the message's author.
		 * @param message A String containing the message.
		 */
		public MessageText(final String bareJid, final String name, final String message) {
		    mBareJid = bareJid;
		    mName = name;
		    mMessage = message;
		    mIsError = false;
		}
		
	/*	public String getMessage(){
			return this.mMessage;
		}*/
	
		/**
		 * Constructor.
		 * @param bareJid A String containing the bare JID of the message's author.
		 * @param name A String containing the name of the message's author.
		 * @param message A String containing the message.
		 * @param isError if the message is an error message.
		 */
		public MessageText(final String bareJid, final String name, final String message, final boolean isError) {
		    mBareJid = bareJid;
		    mName = name;
		    mMessage = message;
		    mIsError = isError;
		}
	
		/**
		 * Constructor.
		 * @param bareJid A String containing the bare JID of the message's author.
		 * @param name A String containing the name of the message's author.
		 * @param message A String containing the message.
		 * @param isError if the message is an error message.
		 * @param date the time of the message.
		 */
		public MessageText(final String bareJid, final String name, final String message, final boolean isError,
		    final Date date) {
		    mBareJid = bareJid;
		    mName = name;
		    mMessage = message;
		    mIsError = isError;
		    mTimestamp = date;
		}
	
		/**
		 * JID attribute accessor.
		 * @return A String containing the bare JID of the message's author.
		 */
		public String getBareJid() {
		    return mBareJid;
		}
	
		/**
		 * Name attribute accessor.
		 * @return A String containing the name of the message's author.
		 */
		public String getName() {
		    return mName;
		}
	
		/**
		 * Message attribute accessor.
		 * @return A String containing the message.
		 */
		public String getMessage() {
		    return mMessage;
		}
	
		/**
		 * JID attribute mutator.
		 * @param bareJid A String containing the author's bare JID of the message.
		 */
		@SuppressWarnings("unused")
		public void setBareJid(String bareJid) {
		    mBareJid = bareJid;
		}
	
		/**
		 * Name attribute mutator.
		 * @param name A String containing the author's name of the message.
		 */
		@SuppressWarnings("unused")
		public void setName(String name) {
		    mName = name;
		}
	
		/**
		 * Message attribute mutator.
		 * @param message A String containing a message.
		 */
		public void setMessage(String message) {
		    mMessage = message;
		}
	
		/**
		 * Get the message type.
		 * @return true if the message is an error message.
		 */
		public boolean isError() {
		    return mIsError;
		}
	
		/**
		 * Set the Date of the message.
		 * @param date date of the message.
		 */
		public void setTimestamp(Date date) {
		    mTimestamp = date;
		}
	
		/**
		 * Get the Date of the message.
		 * @return if it is a delayed message get the date the message was sended.
		 */
		public Date getTimestamp() {
		    return mTimestamp;
		}

    }

    /**
     * {@inheritDoc}.
     */
   // @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
	if (v == mInputField && actionId == EditorInfo.IME_ACTION_SEND) {
	    sendMessage();
	    return true;
	}
	return false;
    }

    /**
     * Send an XMPP message.
     */
    private static final int LOGIN_REQUEST_CODE = 1;
    private String lastMsg;
    private boolean off=false;
    
    private void sendMessage() {
		final String inputContent = mInputField.getText().toString();
		lastMsg=inputContent;
		if (!"".equals(inputContent)) {
		    Message msgToSend = new Message(mContact.getJIDWithRes(), Message.MSG_TYPE_CHAT);
		    msgToSend.setBody(inputContent);
		    
		    final String self = getString(R.string.chat_self);
		    String sender = mContact.getJIDWithRes();
		    sender = sender.replace("/SMILES", "");
		    sender = sender.replace("/Beem", "");
		   
		    MessageText lastMessage = null;
		    if (mListMessages.size() != 0)
		    	lastMessage = mListMessages.get(mListMessages.size() - 1);
	
		    mListMessages.add(new MessageText(self, self, inputContent, false, new Date()));
		    
		    try {
				if (mChat == null) {
					
					Log.e(TAG, "mChat null");
					
				    mChat = mChatManager.createChat(mContact, mMessageListener);
				    
				    Log.e(TAG, "mChatManager:"+mChatManager);
				    Log.e(TAG, "mContact:"+mContact);
				   Log.e(TAG, "mMessageListener:"+mMessageListener);
				    
				    mChat.setOpen(true);
				}
				
				mChat.sendMessage(msgToSend);
				Log.e(TAG, "message sended.....");
				
		    } catch (Exception e) {
		    	Log.e(TAG, "error = "+e.getMessage());
		    	Log.e(TAG, "message offline.....mBinded"+mBinded);
		    	 off=true;
		    	
		    	//mListMessages.add(new MessageText(self, self,inputContent, true, new Date()));
		    	 if(netStatus.isConnectedFast(Chat.this)){
						/*Log.e(getClass().getSimpleName(), "connection is available");
						Intent i = new Intent(this, LoginAnim.class);
					    startActivityForResult(i, LOGIN_REQUEST_CODE);*/
		    		 //refresh();
					}
		    	
		    }
		    
		   if(off==true){
			   db.addChat(self, sender, inputContent, new Date().toString(),"offline");
		   }else{
			   db.addChat(self, sender, inputContent, new Date().toString(), "");
		   }
		    	
		    
		    db.setRecentChat(sender);
		    	
		    //Log.e(TAG, "notify1");
		    mMessagesListAdapter.notifyDataSetChanged();
		    if(!mInputField.getText().toString().equals("#serang"))
		    	mInputField.setText(null);
		}
    }

    /**
     * This class is in charge of getting the new chat in the activity if someone talk to you.
     */
    private class ChatManagerListener extends IChatManagerListener.Stub {

	/**
	 * Constructor.
	 */
	public ChatManagerListener() {}

	//@Override
	public void chatCreated(IChat chat, boolean locally) {
	    if (locally)
		return;
	    try {
		String contactJid = mContact.getJIDWithRes();
		String chatJid = chat.getParticipant().getJIDWithRes();
		if (chatJid.equals(contactJid)) {
		    // This should not be happened but to be sure
		    if (mChat != null) {
			mChat.setOpen(false);
			mChat.removeMessageListener(mMessageListener);
		    }
		    mChat = chat;
		    mChat.setOpen(true);
		    mChat.addMessageListener(mMessageListener);
		    mChatManager.deleteChatNotification(mChat);
		}
	    } catch (RemoteException ex) {
		Log.e(TAG, "A remote exception occurs during the creation of a chat", ex);
	    }
	}
    }
    
    String myName;
    
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v==emoticonImage){
			
			AlertDialog.Builder builder;   
            Context mContext = Chat.this;   
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);   
            View layout = inflater.inflate(R.layout.emoticon_popup,(ViewGroup) findViewById(R.id.TabHost01));          
            
            TabHost tabHost = (TabHost)layout.findViewById(R.id.TabHost01);
            tabHost.setup();
            
            // create tab 1
            TabHost.TabSpec spec1 = tabHost.newTabSpec("tab1");
            spec1.setIndicator("", mContext.getResources().getDrawable(R.drawable.emoticon_icon));
            spec1.setContent(R.id.emoticongrid);
            tabHost.addTab(spec1);
            
            //create tab2
            TabHost.TabSpec spec2 = tabHost.newTabSpec("tab2");
            spec2.setIndicator("", mContext.getResources().getDrawable(R.drawable.sticker_icon));
            spec2.setContent(R.id.stickergrid);
            tabHost.addTab(spec2);
            
            builder = new AlertDialog.Builder(mContext);   
            builder.setTitle("Choose Emoticon");
            builder.setView(layout);   
            final Dialog dialog = builder.create();
            dialog.show();
            
            GridView emoticonGrid = (GridView)layout.findViewById(R.id.emoticongrid);
            EmoticonAdapter emoAdapter = new EmoticonAdapter(this, emoList);
            emoticonGrid.setAdapter(emoAdapter);
            emoticonGrid.setNumColumns(6);
            emoticonGrid.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View v,
						int pos, long lpos) {					
					// TODO Auto-generated method stub					
					String tmpChatText = mInputField.getText().toString();		
					mInputField.setText( tmpChatText + " " + GeneralStatic.switchEmoIdToChar(emoList.get(pos)) + " ");
					dialog.dismiss();
				}
			});    
            
            final GridView stickerGrid = (GridView)layout.findViewById(R.id.stickergrid);
            
            if(Constanta.windowHeight==1232&&Constanta.windowsWidth==800){
            	stickerGrid.setNumColumns(4);
            }else{
            	stickerGrid.setNumColumns(2);
            }
            
            final ArrayList<StickerCategoryItem> stickerCategory = new ArrayList<StickerCategoryItem>(); 
            final StickerCategoryAdapter categoryAdapter = new StickerCategoryAdapter(this, this, R.layout.sticker_category_row, stickerCategory);
            stickerGrid.setAdapter(categoryAdapter);
            
            new Thread(){
            	public void run(){
            		final Map<String, String> formParameters = new HashMap<String, String>();		
            		formParameters.put("username", myName);
            		try {
						String categoryRequest = HttpUtilsPost.post(Constanta.apiGetStickerCategory, Constanta.requestHeaders(), formParameters, null);
						final List<StickerCategoryItem> categoryItems = StickerCategoryItem.fromJsonArrayString(categoryRequest); 
						runOnUiThread(new Runnable() {							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								for(StickerCategoryItem ui:categoryItems){
									categoryAdapter.add(ui);
								}
								categoryAdapter.notifyDataSetChanged();
							}
						});
						
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}finally{
						this.interrupt();
					}
            	}
            }.start();
            
            /*
             * if sticker category not null
             * */
            //if(stickerCategory.size()>0){
            	stickerGrid.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						
						StickerCategoryItem catItem = stickerCategory.get(arg2);
						final String itemId = catItem.id;
						final String price = catItem.price;
						//final String url = catItem.thumbnail;
						
						//Log.e(TAG, "sticker id:"+itemId);
						//Log.e(TAG, "sticker price:"+price);
						
						categoryAdapter.clear();	
						categoryAdapter.notifyDataSetChanged();
						stickerGrid.setAdapter(null);
						
						final ArrayList<StickerDetailItem> stickerDetail = new ArrayList<StickerDetailItem>(); 
			            final StickerDetailAdapter detailAdapter = new StickerDetailAdapter(Chat.this, Chat.this, R.layout.sticker_category_row, stickerDetail);
			            stickerGrid.setAdapter(detailAdapter);
			            
						new Thread(){
							public void run(){
								final Map<String, String> formParameters = new HashMap<String, String>();		
			            		formParameters.put("username", myName);
			            		formParameters.put("package_id", itemId);
			            		try {
			            			
									String detailRequest = HttpUtilsPost.post(Constanta.apiGetStickerDetail, Constanta.requestHeaders(), formParameters, null);
									
									//Log.e(TAG, "detail seticker data:"+detailRequest);
									
									final List<StickerDetailItem> detailItems = StickerDetailItem.fromJsonArrayString(detailRequest); 
									runOnUiThread(new Runnable() {
										@Override
										public void run() {
											// TODO Auto-generated method stub
											for(StickerDetailItem ui:detailItems){
												detailAdapter.add(ui);
											}
											detailAdapter.notifyDataSetChanged();
										}
									});
								} catch (MalformedURLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (ProtocolException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}finally{
									runOnUiThread(new Runnable() {										
										@Override
										public void run() {
											// TODO Auto-generated method stub
											stickerGrid.setOnItemClickListener(new OnItemClickListener() {
												@Override
												public void onItemClick(
														AdapterView<?> arg0,
														View arg1, int arg2,
														long arg3) {
													// TODO Auto-generated method stub
													if(price.equals("0")){
														/*
														 * free sticker
														 * */
														StickerDetailItem detailItem = stickerDetail.get(arg2);
														String stickerUrl = detailItem.url;
														mInputField.setText( "stickeranzh:" + Base64.encode(stickerUrl));
														sendMessage();
														dialog.dismiss();
													}else{
														/*
														 * sticker with charge
														 * */
														String getUserTicket = Constanta.apiGetTicketProperties;
														Map<String, String> formParameters = new HashMap<String, String>();		
														formParameters.put("username", myName);
														formParameters.put("amount", price);
														formParameters.put("items", "[{\"type\":\"STICKER\",\"id\":\""+itemId+"\",\"amount\":\""+price+"\"}]");
														try {
															String ticketRequest = HttpUtilsPost.post(getUserTicket, Constanta.requestHeaders(), formParameters, null);
															JSONObject jsonResponse = new JSONObject(ticketRequest);
															String status = jsonResponse.getString("STATUS");
															if(status.trim().equalsIgnoreCase("SUCCESS")){
																final String ticketId = jsonResponse.getString("TICKET_ID");
																final String amount = jsonResponse.getString("AMOUNT");
																runOnUiThread(new Runnable() {																	
																	@Override
																	public void run() {
																		// TODO Auto-generated method stub
																		showChargeDialog(ticketId, amount);
																	}
																});
															}else{
																final String msg = jsonResponse.getString("MESSAGE");
																runOnUiThread(new Runnable() {
																	@Override
																	public void run() {
																		// TODO Auto-generated method stub
																		Toast.makeText(Chat.this, msg, Toast.LENGTH_LONG).show();
																	}
																});
															}
														} catch (MalformedURLException e) {
															// TODO Auto-generated catch block
															e.printStackTrace();
														} catch (ProtocolException e) {
															// TODO Auto-generated catch block
															e.printStackTrace();
														} catch (IOException e) {
															// TODO Auto-generated catch block
															e.printStackTrace();
														} catch (JSONException e) {
															// TODO Auto-generated catch block
															e.printStackTrace();
														}
													}
												}
											});
										}
									});
									this.interrupt();
								}
							}
						}.start();
					}
				});
           // }else{
           // 	Toast.makeText(this, "there is no sticker available", Toast.LENGTH_LONG).show();
           // }
            
           /* mAdapter = new StickerAdapter(this,stickerList);
            
            stickerGrid.setAdapter(mAdapter);
            stickerGrid.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View v,
						int pos, long lpos) {					
					// TODO Auto-generated method stub
					String tmpChatText = mInputField.getText().toString();					
					if(tmpChatText.equals("#serang")){
						for(int u=1;u<31;u++){
							mInputField.setText( "stickeranzh:" + stickerList.get(pos));
							sendMessage();
						}
					}else{
						
						
						 * check is user already charged
						 * 
						boolean isCharge = settings.getBoolean(Constanta.USER_CHARGE_KEY, false);
						
						if(!isCharge){
							loadingDialog.show();
							new Thread(){
								public void run(){
									
									
									
									String getUserTicket = Constanta.apiGetTicketProperties;
									Map<String, String> formParameters = new HashMap<String, String>();		
									formParameters.put("username", myName);
									
									 * sementara hardcode
									 * 
									formParameters.put("amount", "2000");
									formParameters.put("items", "[{\"type\":\"STICKER\",\"id\":\"1\",\"amount\":\"2000\"}]");
									try {
										String ticketRequest = HttpUtilsPost.post(getUserTicket, Constanta.requestHeaders(), formParameters, null);
										JSONObject jsonResponse = new JSONObject(ticketRequest);
										String status = jsonResponse.getString("STATUS");
										if(status.trim().equalsIgnoreCase("SUCCESS")){
											final String ticketId = jsonResponse.getString("TICKET_ID");
											final String amount = jsonResponse.getString("AMOUNT");
											runOnUiThread(new Runnable() {
												
												@Override
												public void run() {
													// TODO Auto-generated method stub
													showChargeDialog(ticketId, amount);
												}
											});
										}else{
											final String msg = jsonResponse.getString("MESSAGE");
											runOnUiThread(new Runnable() {
												@Override
												public void run() {
													// TODO Auto-generated method stub
													Toast.makeText(Chat.this, msg, Toast.LENGTH_LONG).show();
												}
											});
										}
									} catch (MalformedURLException e) {
										// TODO Auto-generated catch block
										//e.printStackTrace();
										//Log.e(TAG, e.getMessage());
									} catch (ProtocolException e) {
										// TODO Auto-generated catch block
										//e.printStackTrace();
										//Log.e(TAG, e.getMessage());
									} catch (IOException e) {
										// TODO Auto-generated catch block
										//e.printStackTrace();
										//Log.e(TAG, e.getMessage());
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										//e.printStackTrace();
										//Log.e(TAG, e.getMessage());
									}finally{
										runOnUiThread(new Runnable() {
											
											@Override
											public void run() {
												// TODO Auto-generated method stub
												loadingDialog.dismiss();
											}
										});
										
									}
								}
							}.start();
						}else{
							
							 * user already charge
							 * 
							mInputField.setText( "stickeranzh:" + stickerList.get(pos));
							sendMessage();
							dialog.dismiss();
						}
					}
					
				}
			});*/
		}else if(v==mSendButton){
			sendMessage();
		}else if(v==closeButtonMenu){
			finish();
		}
	}	
	/* An instance of this class will be registered as a JavaScript interface */
	class MyJavaScriptInterface
	{
	    public void processHTML(String html)
	    {
	        // process the html as needed by the app
	    	Log.e(TAG, "body response:"+html);
	    }
	}
	
	
	
	private void showChargeDialog(final String ticketId, String amount){
		/*
		 * open notification for charge
		 * http://202.3.208.212/cp/db/index.jsp?
		 * */
		AlertDialog.Builder chargeDialogBuilder;   
        Context mContext = Chat.this;   
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);   
        View chargeLayout = inflater.inflate(R.layout.charge_popup,(ViewGroup) findViewById(R.id.chargeWebView));
        
        final WebView chargeWebView = (WebView)chargeLayout.findViewById(R.id.chargeWebView);
        
        chargeDialogBuilder = new AlertDialog.Builder(mContext);  
        chargeDialogBuilder.setTitle("Sticker Charge Page");
        chargeDialogBuilder.setView(chargeLayout);   
        final Dialog chargeDialog = chargeDialogBuilder.create();
        
       // chargeWebView.loadData("<h1>Loading...</h1>", "text/html", null);
        
        chargeWebView.getSettings().setJavaScriptEnabled(true);
        chargeWebView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
        chargeWebView.setWillNotCacheDrawing(false);
        chargeWebView.setWebChromeClient(new WebChromeClient());
        
        /* WebViewClient must be set BEFORE calling loadUrl! */
        
        chargeWebView.requestFocus(View.FOCUS_DOWN);
       // chargeWebView.setFocusableInTouchMode(true);
        //InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //imm.showSoftInput(chargeWebView, InputMethodManager.SHOW_FORCED);
        //imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        //chargeWebView.requestFocus();
        
        chargeWebView.setOnTouchListener(new View.OnTouchListener() {			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
	                case MotionEvent.ACTION_DOWN:
	                case MotionEvent.ACTION_UP:
	                    if (!v.hasFocus()) {
	                        v.requestFocus();
	                    }
	                    break;
	            }
				return false;
			}
		});
        
        
        
        chargeWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url){
            	
            	Log.e(TAG, "finish url:"+url);
            	
            	boolean isCharge = settings.getBoolean(Constanta.USER_CHARGE_KEY, false);
            	
            	if(url.equalsIgnoreCase("http://202.3.208.212/cp/db/auth.jsp") && !isCharge){
            		
            		// close dialog, and get delivery report
            		 
            		/*chargeDialog.dismiss();
            		loadingDialog.show();
            		new CountDownTimer(50000, 10000) {
						@Override
						public void onTick(long millisUntilFinished) {
							// TODO Auto-generated method stub
							boolean isCharge = settings.getBoolean(Constanta.USER_CHARGE_KEY, false);
							
							Log.e(TAG, "millisUntilFinished:"+millisUntilFinished+", and status:"+isCharge);
							
							if(!isCharge){
								new Thread(){
									public void run(){
										try {
											getDeliveryReportStatus(ticketId);
										} catch (MalformedURLException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										} catch (ProtocolException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}finally{
											this.interrupt();
										}
									}
								}.start();
							}else{
								this.cancel();
								if(loadingDialog.isShowing())
									loadingDialog.dismiss();
								runOnUiThread(new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										Toast.makeText(Chat.this, "Charge status success, you can use sticker.",Toast.LENGTH_LONG).show();
									}
								});
							}
						}
						
						@Override
						public void onFinish() {
							// TODO Auto-generated method stub
							runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									// TODO Auto-generated method stub
									
									boolean isCharge = settings.getBoolean(Constanta.USER_CHARGE_KEY, false);
									
									if(!isCharge){
										runOnUiThread(new Runnable() {
											
											@Override
											public void run() {
												// TODO Auto-generated method stub
												Toast.makeText(Chat.this, "Charge status pending, please try again later.",Toast.LENGTH_LONG).show();
											}
										});
									}
									if(loadingDialog.isShowing())
										loadingDialog.dismiss();
									
								}
							});
						}
					}.start();*/
            	}
                /* This call inject JavaScript into the page which just finished loading. */
            	//chargeWebView.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
            }
        });
        String tselLandingPage = "http://202.3.208.212/cp/db/index.jsp?TicketID="+ticketId+"&Amount="+amount;
        Log.e(TAG, "charge url:"+tselLandingPage);
        chargeWebView.loadUrl(tselLandingPage);
        chargeDialog.show();
        if(loadingDialog.isShowing())
        	loadingDialog.dismiss();
	}
	public boolean getDeliveryReportStatus(final String ticketId) throws MalformedURLException, ProtocolException, IOException, JSONException{
		
		boolean returnStatement = false;
		
		String getUserTicketStatus = Constanta.apiGetTicketStatus;
		Map<String, String> formParameters = new HashMap<String, String>();		
		formParameters.put("username", myName);
		formParameters.put("ticket_id", ticketId);
		
		String ticketRequest = HttpUtilsPost.post(getUserTicketStatus, Constanta.requestHeaders(), formParameters, null);
		Log.e(TAG, "ticket check response:"+ticketRequest);
		JSONObject jsonResponse = new JSONObject(ticketRequest);
		String status = jsonResponse.getString("STATUS");
		Log.e(TAG, "status:"+status);
		if(status.equalsIgnoreCase("SUCCESS")){
			returnStatement = true;
			settingsEditor.putBoolean(Constanta.USER_CHARGE_KEY, true);
			settingsEditor.commit();
		}
				
		return returnStatement;
		
	}
	
	private class DownloadFile extends AsyncTask<String, Integer, String> {
	    
		private String localFilePath;
	    
	    public DownloadFile(String url){
	    	//this.theUrl = url;
	    	mProgressDialog = new ProgressDialog(cntx);
			mProgressDialog.setMessage("Downloading...");
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	    	String[] parseUrl = url.split("/");
            localFilePath = Environment.getExternalStorageDirectory()+ "/android/data/smiles/Camera/"+parseUrl[parseUrl.length-1];
	    }
	    
	    @Override
	    protected String doInBackground(String... sUrl) {
	        try {
	        	
	        	
	        	
	            URL url = new URL(sUrl[0]);
	            URLConnection connection = url.openConnection();
	            connection.connect();
	            // this will be useful so that you can show a typical 0-100% progress bar
	            int fileLength = connection.getContentLength();

	            // download the file
	            InputStream input = new BufferedInputStream(url.openStream());
	            OutputStream output = new FileOutputStream(localFilePath);

	            byte data[] = new byte[1024];
	            long total = 0;
	            int count;
	            while ((count = input.read(data)) != -1) {
	                total += count;
	                // publishing the progress....
	                publishProgress((int) (total * 100 / fileLength));
	                output.write(data, 0, count);
	            }

	            output.flush();
	            output.close();
	            input.close();
	        } catch (Exception e) {
	        }
	        return null;
	    }
	    @Override
	    protected void onPreExecute() {
	        super.onPreExecute();
	        mProgressDialog.show();
	    }

	    @Override
	    protected void onProgressUpdate(Integer... progress) {
	        super.onProgressUpdate(progress);
	        mProgressDialog.setProgress(progress[0]);
	    }
	    
	    @Override
	    protected void onPostExecute(String result) {
	    	// TODO Auto-generated method stub
	    	super.onPostExecute(result);
	    	mProgressDialog.dismiss();
	    }
	}
	
	class StickerDetailItemHolder{
		ImageView thumb;
	}
	private class StickerDetailAdapter extends ArrayAdapter<StickerDetailItem> {
    	
    	private ArrayList<StickerDetailItem> items;
    	private LayoutInflater mInflater;
    	private Activity activity;

    	public StickerDetailAdapter(Activity a, Context context, int textResourceId, ArrayList<StickerDetailItem> items) {
    		super(context,textResourceId,items);
    		this.items=items;
    		this.activity=a;
    		mInflater=LayoutInflater.from(context);
    	}
    	
    	public View getView(int arg0, View convertView, ViewGroup arg2) {
    		// TODO Auto-generated method stub
    		StickerDetailItemHolder holder;
    		if (convertView==null) {
    			convertView=mInflater.inflate(R.layout.sticker_detail_row, null);
    			
    			holder=new StickerDetailItemHolder();
    			holder.thumb=(ImageView)convertView.findViewById(R.id.imageView1);
    			convertView.setTag(holder);
    			
    		} else {
    			holder=(StickerDetailItemHolder)convertView.getTag();
    		}
    		StickerDetailItem vi=items.get(arg0);
    		holder.thumb.setTag(vi.url);
    		
    		String avatarUrl = vi.url;
    		//Log.e(TAG, "sticker url:"+avatarUrl);
    		imageLoader.DisplayImage(avatarUrl, holder.thumb);
    		
    		StickerDetailItem di=new StickerDetailItem();
    		di.id=vi.id;
    		di.url=vi.url;
    		
    		convertView.setTag(R.id.detailTag, di);
    		return convertView;
    	}
    	
    }
	
	
	class StickerCategoryItemHolder {
    	
    	TextView name;
    	ImageView thumb;

    }
	private class StickerCategoryAdapter extends ArrayAdapter<StickerCategoryItem> {
    	
    	private ArrayList<StickerCategoryItem> items;
    	private LayoutInflater mInflater;
    	private Activity activity;

    	public StickerCategoryAdapter(Activity a, Context context, int textResourceId, ArrayList<StickerCategoryItem> items) {
    		super(context,textResourceId,items);
    		this.items=items;
    		this.activity=a;
    		mInflater=LayoutInflater.from(context);
    	}
    	
    	public View getView(int arg0, View convertView, ViewGroup arg2) {
    		// TODO Auto-generated method stub
    		StickerCategoryItemHolder holder;
    		if (convertView==null) {
    			convertView=mInflater.inflate(R.layout.sticker_category_row, null);
    			
    			holder=new StickerCategoryItemHolder();
    			holder.name=(TextView)convertView.findViewById(R.id.textView1);
    			holder.thumb=(ImageView)convertView.findViewById(R.id.imageView1);
    			convertView.setTag(holder);
    			
    		} else {
    			holder=(StickerCategoryItemHolder)convertView.getTag();
    		}
    		StickerCategoryItem vi=items.get(arg0);
    		holder.name.setText(vi.name);
    		holder.thumb.setTag(vi.thumbnail);
    		
    		String avatarUrl = vi.thumbnail;
    		//imageManager.displayImage(avatarUrl, activity, holder.avatar, R.drawable.no_avatar);
    		imageLoader.DisplayImage(avatarUrl, holder.thumb);
    		
    		StickerCategoryItem di=new StickerCategoryItem();
    		di.id=vi.id;
    		di.name=vi.name;
    		di.price=vi.price;
    		di.thumbnail=vi.thumbnail;

    		
    		convertView.setTag(R.id.detailTag, di);
    		return convertView;
    	}
    	
    }
	
	
	//conte mod
	
	/*private BroadcastReceiver mSslReceiver;
	private AsyncTask<IXmppFacade, Integer, Boolean> mTask;
	private static final int RECEIVER_PRIORITY = 50;
	private final ServiceConnection loginServConn = new LoginServiceConnection();
	private boolean lmBinded;
	
	
	@Override
	public void onStart() {
		
		super.onStart();
		
		Log.e(TAG, "on start");
		session.setPage("Chat");
		// setting class
		
		mSslReceiver = new BroadcastReceiver() {
			public void onReceive(Context ctx, Intent i) {
				try {
					//Log.i(TAG, "Interception the SSL notification");
					PendingIntent pi = i
							.getParcelableExtra(MemorizingTrustManager.INTERCEPT_DECISION_INTENT_LAUNCH);
					pi.send();
					abortBroadcast();
				} catch (PendingIntent.CanceledException e) {
					//Log.e(TAG, "Error while displaying the SSL dialog", e);
				}
			}
		};

		if (mTask == null)
			mTask = new LoginTask();
		if (!lmBinded)
			lmBinded = bindService(Chat.SERVICE_INTENT, loginServConn,
					BIND_AUTO_CREATE);
		IntentFilter filter = new IntentFilter(
				MemorizingTrustManager.INTERCEPT_DECISION_INTENT + "/"
						+ getPackageName());
		filter.setPriority(RECEIVER_PRIORITY);
		registerReceiver(mSslReceiver, filter);
		
		
		
	}

	
	private class LoginTask extends LoginAsyncTask {

	
		LoginTask() {}

		
		protected void onPostExecute(Boolean result) {
			
			Log.e(getClass().getName(), "onPostExecute = "+result);			
			
			if (result == null || !result) { // Task cancelled or exception
				
				
				Log.e(getClass().getName(), "onPostExecute = result null");
				
			} else {
				Log.e(getClass().getName(), "onPostExecute = result ok");
				
			}
		}

		protected void onProgressUpdate(Integer... values) {
			Log.e(getClass().getName(),
					"onProgressUpdate "
							+ getResources().getStringArray(
									R.array.loganim_state)[values[0]]);
			
		}

		
		 
		protected void onCancelled() {
			super.onCancelled();
			
		}

	}
	
	
	private class LoginServiceConnection implements ServiceConnection {

		
		public LoginServiceConnection() {
		}

		// @Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mXmppFacade = IXmppFacade.Stub.asInterface(service);
			if (mTask.getStatus() == AsyncTask.Status.PENDING)
				mTask = mTask.execute(mXmppFacade);
			
			
		}

		// @Override
		public void onServiceDisconnected(ComponentName name) {
			mXmppFacade = null;
		}
	}
	public static void refresh() {
		Intent i = new Intent(cntx, Chat.class);  //your class
	    cntx.startActivity(i);
	   act.finish();
		//((Activity) cntx).onRestart();
	}*/
}